import gradio as gr
from paddleocr import PaddleOCR, draw_ocr
from PIL import Image
import numpy as np

# 初始化 PaddleOCR
ocr = PaddleOCR(use_angle_cls=True, lang="ch")


def recognize_text(image_path):
    # 进行 OCR 处理
    result = ocr.ocr(image_path, cls=True)

    # 加载图片
    image = Image.open(image_path).convert('RGB')

    # 获取结果中的边界框、文本和分数
    boxes = [line[0] for line in result[0]]
    txts = [line[1][0] for line in result[0]]
    scores = [line[1][1] for line in result[0]]

    # 绘制 OCR 结果
    im_show = draw_ocr(np.array(image), boxes, txts, scores, font_path='./fonts/simfang.ttf')
    im_show = Image.fromarray(im_show)

    # 返回处理后的图片
    return im_show


# 创建 Gradio 接口
iface = gr.Interface(fn=recognize_text, inputs='image', outputs='image', title="PaddleOCR 文字识别")

# 启动服务
iface.launch(share=True)